## Mikael Poul Johannesson
## 2024

## Start matter ------------------------------------------------------

library(here)
library(haven)
library(tidyverse)
library(patchwork)
library(readxl)

#' Project theme for ggplot2.
#'
#' @importFrom ggplot2 theme element_text element_line margin element_blank
#' @importFrom grid unit
#'
#' @param ... Other arguments passed to \code{theme()}.
#'
#' @export
theme_m <- function(...) {
  theme(
    text = element_text(size = 10,
                        colour = "black"),
    axis.text = element_text(size = 10,
                             colour = "black"),
    axis.title = element_text(size = 10,
                              colour = "black"),
    axis.line = element_line(),
    axis.ticks = element_line(colour = "black"),
    axis.ticks.length = unit(1, "mm"),
    plot.margin = margin(1, 5, 1, 1, "mm"),
    panel.spacing.x = unit(7.5, "mm"),
    panel.spacing.y = unit(2, "mm"),
    panel.background = element_blank(),
    panel.grid.major = element_blank(),
    strip.background = element_blank(),
    strip.text = element_text(size = 9, face = "bold"),
    ## strip.text.y = element_text(angle = 0, face = "bold.italic"),
    strip.text.y = element_blank(),
    legend.background = element_blank(),
    legend.key = element_blank(),
    legend.position = "bottom",
    legend.title = element_text(size = 10, face = "bold"),
    legend.key.height = unit(4, "mm"),
    legend.title.align = .125,
    legend.margin = margin(),
    plot.tag = element_text(size = 11, face = "bold"),
    ...
  )
}


## Data --------------------------------------------------------------

## pop_raw <- readxl::read_excel(
##   here::here("raw", "07459_20240821-140932.xlsx"),
##   skip = 4
## )

## fo_raw <- readRDS(here::here("data", "fo_raw.rds"))

## pop <-
##   pop_raw %>%
##   rename(county = `...1`, age = `...2`) %>%
##   fill(county) %>%
##   pivot_longer(
##     cols = c(Menn, Kvinner),
##     names_to = "gender", values_to = "n"
##   ) %>%
##   mutate(
##     county = case_when(
##       grepl("Oslo", county) ~ "Oslo",
##       grepl("Rogaland", county) ~ "Rogaland",
##       grepl("Møre og Romsdal", county) ~ "Møre og Romsdal",
##       grepl("Nordland", county) ~ "Nordland",
##       grepl("Svalbard", county) ~ "Svalbard",
##       grepl("Viken", county) ~ "Viken",
##       grepl("Innlandet", county) ~ "Innlandet",
##       grepl("Vestfold og Telemark", county) ~ "Vestfold og Telemark",
##       grepl("Agder", county) ~ "Agder",
##       grepl("Vestland", county) ~ "Vestland",
##       grepl("Trøndelag", county) ~ "Trøndelag",
##       grepl("Troms og Finnmark", county) ~ "Troms og Finnmark"),
##     gender = case_when(
##       gender == "Kvinner" ~ "Female",
##       gender == "Menn" ~ "Male"),
##     age = extract_numeric(age),
##     age_gr = case_when(
##     age %in% 18:19 ~ "18-19 år",
##     age %in% 20:29 ~ "20-29 år",
##     age %in% 30:39 ~ "30-39 år",
##     age %in% 40:49 ~ "40-49 år",
##     age %in% 50:59 ~ "50-59 år",
##     age %in% 60:69 ~ "60-69 år",
##     age %in% 70:79 ~ "70-79 år",
##     age %in% 80:89 ~ "80-89 år",
##     age %in% 90:99 ~ "90-99 år",
##     age >= 100 ~ "100 år eller eldre")
##   ) %>%
##   filter(!is.na(age_gr)) %>%
##   group_by(county, gender, age_gr) %>%
##   summarize(n = sum(n)) %>%
##   ungroup() %>%
##   mutate(
##     nn = sum(n),
##     prop_pop = n / nn)

## fo_raw_we <-
##   fo_raw %>%
##   mutate_at(
##     vars(fg_kunnskap_1, fg_kunnskap_2, fg_kunnskap_3),
##     function(x) 8 - x
##   ) %>%
##   mutate(
##     age_gr = case_when(
##       age %in% 18:19 ~ "18-19 år",
##       age %in% 20:29 ~ "20-29 år",
##       age %in% 30:39 ~ "30-39 år",
##       age %in% 40:49 ~ "40-49 år",
##       age %in% 50:59 ~ "50-59 år",
##       age %in% 60:69 ~ "60-69 år",
##       age %in% 70:79 ~ "70-79 år",
##       age %in% 80:89 ~ "80-89 år",
##       age %in% 90:99 ~ "90-99 år",
##       age >= 100 ~ "100 år eller eldre")
##   ) %>%
##   filter(fg_kjennskap_nav %in% 1:7) %>%
##   count(county, gender, age_gr) %>%
##   mutate(
##     nn = sum(n),
##     prop = n / nn
##   ) %>%
##   left_join(pop %>% select(-n, -nn)) %>%
##   mutate(we = prop_pop / prop) %>%
##   select(county, gender, age_gr, we)

## saveRDS(
##   fo_raw_we %>% select(we),
##   here::here("data", "fo_raw_we_only.rds")
## )

estimate_we_did <- function(var) {

  data <- fo_raw
  data$var <- data[[var]]

fo_raw_we_new <-
  data %>%
  mutate(
    age_gr = case_when(
      age %in% 18:19 ~ "18-19 år",
      age %in% 20:29 ~ "20-29 år",
      age %in% 30:39 ~ "30-39 år",
      age %in% 40:49 ~ "40-49 år",
      age %in% 50:59 ~ "50-59 år",
      age %in% 60:69 ~ "60-69 år",
      age %in% 70:79 ~ "70-79 år",
      age %in% 80:89 ~ "80-89 år",
      age %in% 90:99 ~ "90-99 år",
      age >= 100 ~ "100 år eller eldre")
  ) %>%
  filter(var %in% 1:7) %>%
  count(county, gender, age_gr) %>%
  mutate(
    nn = sum(n),
    prop = n / nn
  ) %>%
  left_join(pop %>% select(-n, -nn)) %>%
  mutate(we = prop_pop / prop) %>%
  select(county, gender, age_gr, we)

  data <-
    data %>%
    mutate(
      var = case_when(var %in% 1:7 ~ var),
      age_gr = case_when(
        age %in% 18:19 ~ "18-19 år",
        age %in% 20:29 ~ "20-29 år",
        age %in% 30:39 ~ "30-39 år",
        age %in% 40:49 ~ "40-49 år",
        age %in% 50:59 ~ "50-59 år",
        age %in% 60:69 ~ "60-69 år",
        age %in% 70:79 ~ "70-79 år",
        age %in% 80:89 ~ "80-89 år",
        age %in% 90:99 ~ "90-99 år",
        age >= 100 ~ "100 år eller eldre")
    ) %>%
    left_join(fo_raw_we_new)


  lm(
    var ~ post + fg + post:fg,
    data = data,
    weights = we
  ) %>%
    broom::tidy() %>%
    filter(term == "post:fg") %>%
    mutate(var = var)
}

## APX Fig 4 ---------------------------------------------------------

fo_raw_we_only <- readRDS(here::here("data", "fo_raw_we_only.rds"))

fig_fg_weights <-
  fo_raw_we_only %>%
  ggplot(aes(we)) +
  geom_density() +
  scale_x_log10(
    limits = c(.03125, 4),
    breaks = c(.03125, .0625, .125, .25, .5, 1, 2, 4),
    expand = c(0, 0),
    labels = c("1/32", "1/16", "1/8", "1/4", "1/2", "1", "2", "4")) +
  geom_vline(aes(xintercept = 1), linetype = "dotted") +
  theme_m() +
  labs(
    x = "Design Weights",
    y = "Density",
    caption = "Lowest .06; Highest 2.4"
  )
fig_fg_weights

ggsave(
  here::here("output", "apx_fig_4.pdf"),
  fig_fg_weights,
  width = 5, height = 3
)

ggsave(
  here::here("output", "apx_fig_4.png"),
  fig_fg_weights,
  width = 5, height = 3
)


## APX Fig 5 ---------------------------------------------------------

## att_open_res_we <-
##   c("fg_kjennskap_nav", "fg_kunnskap2", "fg_kjennskap_prv") %>%
##   map_dfr(estimate_we_did) %>%
##   mutate(var = fct_inorder(var)) %>%
##   arrange(var) %>%
##   mutate(
##     lwr = estimate - (1.96 * std.error),
##     upr = estimate + (1.96 * std.error),
##     varlab = case_when(
##       var == "fg_kjennskap_prv" ~ "Parole",
##       var == "fg_kjennskap_nav" ~ "Sick leave dialogue meeting",
##       var == "fg_kunnskap2" ~ "Refugee assignment"),
##     varlab = lvls_reorder(factor(varlab), c(1, 2, 3))
##   ) %>%
##   arrange(varlab)
## # order: sick, refugee, parole

## saveRDS(att_open_res_we, here::here("data", "att_open_res_we.rds"))

att_open_res_we <- readRDS(here::here("data", "att_open_res_we.rds"))

fig_att_open_we <-
  att_open_res_we %>%
  ggplot(aes(
    estimate, varlab, xmin = lwr, xmax = upr,
    shape = p.value < .0505)) +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  geom_errorbarh(height = 0) +
  geom_point(fill = "white") +
  scale_shape_manual(values = c(19, 21)) +
  scale_x_continuous(
    limits = c(-2, 2),
    breaks = seq(-2, 2, .5),
    expand = c(0, 0)) +
  ## scale_y_discrete(labels = function(x) parse(text = x)) +
  theme_m() +
  theme(legend.position = "none") +
  labs(
    x = "Average Treatment Effect on the Treated (ATT)\nof participating in deliberation. WEIGHTED.",
    y = NULL,
    subtitle = str_wrap("Based on your knowledge, how strongly do you support or oppose the Norwegian goverment (/NAV) opening up the use of algortihms for:", 70),
    caption = c("1: Oppose very strongly  --  7: Support very strongly")) +
  theme(plot.subtitle = element_text(face = "bold"))
fig_att_open_we

ggsave(
  here::here("output", "apx_fig_5.pdf"),
  fig_att_open_we,
  width = 7, height = 1.75
)

ggsave(
  here::here("output", "apx_fig_5.png"),
  fig_att_open_we,
  width = 7, height = 1.75
)


## APX Fig 6 ---------------------------------------------------------

## att_know_res_we <-
##   c("fg_kunnskap_1", "fg_kunnskap_2", "fg_kunnskap_3") %>%
##   map_dfr(estimate_we_did) %>%
##   mutate(var = fct_inorder(var)) %>%
##   arrange(var) %>%
##   mutate(
##     lwr = estimate - (1.96 * std.error),
##     upr = estimate + (1.96 * std.error),
##     ## varlab = case_when(
##     ##   var == "fg_kunnskap_1" ~ "Machine leaning (ML) and Artifical intelligence (AI)",
##     ##   var == "fg_kunnskap_2" ~ "How the Norwegian authorities currently decide where refugees will be settled once they have been granted residence in Norway",
##     ##   var == "fg_kunnskap_3" ~ "How NAV currently decides which people on sick leave are to be invited to a dialogue meeting about how they can more easily return to work"),
##     varlab = case_when(
##       var == "fg_kunnskap_1" ~ "Machine leaning (ML) and Artifical intelligence (AI)",
##       var == "fg_kunnskap_2" ~ "Refugee assignment",
##       var == "fg_kunnskap_3" ~ "Sick leave dialogue meeting"),
##     varlab = lvls_reorder(factor(varlab), c(2, 3, 1))
##   ) %>%
##   arrange(varlab)

## saveRDS(att_know_res_we, here::here("data", "att_know_res_we.rds"))

att_know_res_we <- readRDS(here::here("data", "att_know_res_we.rds"))

fig_att_know_we <-
  att_know_res_we %>%
  ggplot(aes(
    estimate, varlab, xmin = lwr, xmax = upr,
    shape = p.value < .0505)) +
  geom_vline(aes(xintercept = 0), linetype = "dotted") +
  geom_errorbarh(height = 0) +
  geom_point(fill = "white") +
  scale_shape_manual(values = c(19, 21)) +
  scale_x_continuous(
    limits = c(-1.5, 1.5),
    breaks = seq(-1.5, 1.5, .5),
    expand = c(0, 0)) +
  ## scale_y_discrete(labels = function(x) parse(text = x)) +
  theme_m() +
  theme(legend.position = "none") +
  labs(
    x = "Average Treatment Effect on the Treated (ATT)\nof participating in deliberation. WEIGHTED.",
    y = NULL,
    #subtitle = "How well would you say you know the following:",
    caption = c("'How well would you say you know the following'\n1: 'No knowledge at all'  --  5: 'Very good knowledge'")) +
  theme(plot.subtitle = element_text(face = "bold"))
fig_att_know_we

ggsave(
  here::here("output", "apx_fig_6.pdf"),
  fig_att_know_we,
  width = 7, height = 1.5
)

ggsave(
  here::here("output", "apx_fig_6.png"),
  fig_att_know_we,
  width = 7, height = 1.5
)

## END ---------------------------------------------------------------
